package cn.ht.jywrwater.module.ht.service.meterdata;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.ht.jywrwater.module.ht.controller.admin.meterdata.vo.*;
import cn.ht.jywrwater.module.ht.dal.dataobject.meterdata.MeterDataDO;
import cn.ht.jywrwater.framework.common.pojo.PageResult;

import cn.ht.jywrwater.module.ht.convert.meterdata.MeterDataConvert;
import cn.ht.jywrwater.module.ht.dal.mysql.meterdata.MeterDataMapper;

import static cn.ht.jywrwater.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.ht.jywrwater.module.ht.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 水表数据 Service 实现类
 *
 * @author hzx
 */
@Service
@Validated
public class MeterDataServiceImpl implements MeterDataService {

    @Resource
    private MeterDataMapper meterDataMapper;

    @Override
    public Long createMeterData(MeterDataCreateReqVO createReqVO) {
        // 插入
        MeterDataDO meterData = MeterDataConvert.INSTANCE.convert(createReqVO);
        meterDataMapper.insert(meterData);
        // 返回
        return meterData.getId();
    }

    @Override
    public void updateMeterData(MeterDataUpdateReqVO updateReqVO) {
        // 校验存在
        validateMeterDataExists(updateReqVO.getId());
        // 更新
        MeterDataDO updateObj = MeterDataConvert.INSTANCE.convert(updateReqVO);
        meterDataMapper.updateById(updateObj);
    }

    @Override
    public void deleteMeterData(Long id) {
        // 校验存在
        validateMeterDataExists(id);
        // 删除
        meterDataMapper.deleteById(id);
    }

    private void validateMeterDataExists(Long id) {
        if (meterDataMapper.selectById(id) == null) {
            throw exception(METER_DATA_NOT_EXISTS);
        }
    }

    @Override
    public MeterDataDO getMeterData(Long id) {
        return meterDataMapper.selectById(id);
    }

    @Override
    public List<MeterDataDO> getMeterDataList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return meterDataMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<MeterDataDO> getMeterDataPage(MeterDataPageReqVO pageReqVO) {
        return meterDataMapper.selectPage(pageReqVO);
    }

    @Override
    public List<MeterDataDO> getMeterDataList(MeterDataExportReqVO exportReqVO) {
        return meterDataMapper.selectList(exportReqVO);
    }

}
